package arithmetic.leetCode;

/**
 * 给定一个正整数 n，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的正方形矩阵。
 * <p>
 * 示例:
 * <p>
 * 输入: 3
 * 输出:
 * [
 * [ 1, 2, 3 ],
 * [ 8, 9, 4 ],
 * [ 7, 6, 5 ]
 * ]
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/spiral-matrix-ii
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 * @author dycong
 * @date 2019/10/16 9:29
 */
public class SpiralMatrix_59 {

    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];

        int left = 0;
        int right = matrix[0].length - 1;

        int top = 0;
        int bottom = matrix.length - 1;

        // TODO: 2019/10/16  counter = 1
        int counter = 1;

        while (true) {
            for (int i = left; i <= right; i++) matrix[top][i] = counter++;
            top++;
            if (left > right || top > bottom) return matrix;

            for (int i = top; i <= bottom; i++) matrix[i][right] = counter++;
            right--;
            if (left > right || top > bottom) return matrix;

            for (int i = right; i >= left; i--) matrix[bottom][i] = counter++;
            bottom--;
            if (left > right || top > bottom) return matrix;

            for (int i = bottom; i >= top; i--) matrix[i][left] = counter++;
            left++;
            if (left > right || top > bottom) return matrix;
        }


    }
}
